import { boot } from 'quasar/wrappers';
import { LocalStorage } from 'quasar';
import { axiosInstance, axiosEle } from 'boot/axios';

const axios = process.env.MODE === 'electron' ? axiosEle : axiosInstance;
// "async" is optional;
// more info on params: https://v2.quasar.dev/quasar-cli/boot-files
export default boot(async ({ app, router }) => {
  // 使用 router.beforeEach 注册一个全局前置守卫，判断用户是否登陆
  router.beforeEach((to, from, next) => {
    if (to.matched.some(record => ['/main', '/cockpit'].includes(record.path))) { // 进入主页，判断是否有token, '/cockpit'
      const token = LocalStorage.getItem('token');
      if (token === null || token === '') {
        let topath = '/';
        if (to.path && to.path !== '/main/index') {
          topath = '/?redirect=' + to.path;
        }
        next(topath);
      } else {
        next();
      }
    } else if (to.matched.some(record => record.path === '/')) { // 进入登录页验证是否登录
      const token = LocalStorage.getItem('token');
      if (token) {
        axios.post('/checkToken', { token }).then(res => {
          if (res.data === 'Authorized') {
            next('/main');
          } else {
            LocalStorage.clear();
            next();
          }
        });
      } else {
        next();
      }
    } else {
      next();
    }
  });
});
